package com.chb.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chb.system.mapper.MenuMapper;
import com.chb.system.service.MenuService;
import com.chb.system.service.UserService;
import com.chb.system.vo.MenuVo;
import com.hos.entity.sys.Menu;
import com.hos.entity.sys.User;
import com.hos.utils.JwtUtils;
import com.hos.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/7 19:37
 * @description:
 * @modified By:
 * @version:
 */
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @Override
    public List<Menu> findMenusBuUserId(Long userId) {
        return menuMapper.selectMenusByUserId(userId);
    }

    @Override
    public List<Menu> selectMenusByRoleId(Long roleId) {
        return menuMapper.selectMenusByRoleId(roleId);
    }

    @Override
    public List<Menu> getLeftMenu() {
        String token = WebUtil.getToken();
        String phone = JwtUtils.getClaimByName(token);

        try {
            // 1.从缓存中查询左侧菜单
            String leftMenu = redisTemplate.opsForValue().get("menu:leftMenu:" + phone);
            if (StringUtils.hasText(leftMenu)) {
                return JSON.parseArray(leftMenu, Menu.class);
            }
        } catch (Exception e) {
            log.error("查询左侧菜单出现异常");
        }
        User user = getUserByToken();

        List<Menu> menus = menuMapper.selectAllMenuByPhone(phone);
        // 1.查询所有的一级菜单
        List<Menu> first = menus.stream().filter(item -> item.getParentId().equals(0L)).collect(Collectors.toList());
        // 2.查询一级菜单下的子菜单
        for (Menu menu : menus) {
            List<Menu> children = new ArrayList<>();
            for (Menu m : menus) {
                if (m.getParentId().equals(menu.getMenuId())) {
                    children.add(m);
                }
            }
            menu.setChildren(children);
        }
        // 2.将数据放入到缓存中
        redisTemplate.opsForValue().set("menu:leftMenu:" + phone, JSON.toJSONString(first));
        return first;
    }

    /**
     * 查询所有的菜单
     *
     * @return
     */
    @Override
    public List<Menu> selectAllMenu() {
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Menu::getStatus, 0);
        // User user = getUserByToken();
        return menuMapper.selectList(wrapper);
    }

    @Override
    public List<Menu> findMuneByCond(MenuVo menuVo) {
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(menuVo.getMenuName())) {
            wrapper.like(Menu::getMenuName, menuVo.getMenuName());
        }
        if (StringUtils.hasText(menuVo.getStatus())) {
            wrapper.eq(Menu::getStatus, menuVo.getStatus());
        }
        return menuMapper.selectList(wrapper);
    }

    // 添加
    @Override
    public Integer addMenu(Menu menu) {

        String token = WebUtil.getToken();
        String phone = JwtUtils.getClaimByName(token);
        // 创建时间
        menu.setCreateTime(new Date());
        menu.setCreateBy(getUserByToken().getUserName());
        if (menu.getParentId() != 0) {
            menu.setParentIds(menu.getParentId().toString());
        }
        // menu.setPercode(menu.getPath().replaceFirst("/", ""));
        // menu.setPercode(menu.getPath().replaceAll("/", ":"));
        String replaceFirst = menu.getPath().replaceFirst("/", "");
        menu.setPercode(replaceFirst.replaceAll("/",":"));

        redisTemplate.delete("menu:leftMenu:" + phone);
        return menuMapper.insert(menu);
    }

    // 删除
    @Override
    public Integer deleteMenuById(Long id) {
        String token = WebUtil.getToken();
        String phone = JwtUtils.getClaimByName(token);
        redisTemplate.delete("menu:leftMenu:" + phone);
        return menuMapper.deleteById(id);
    }

    // 根据菜单ID查询单个菜单
    @Override
    public Menu getMenuById(Long menuId) {
        return menuMapper.selectById(menuId);
    }

    // 修改菜单信息
    @Override
    public Integer updateMenu(Menu menu) {
        menu.setUpdateBy(getUserByToken().getUserName());
        menu.setUpdateTime(new Date());
        // menu.setPercode(menu.getPath().replaceFirst("/", " "));
        // menu.setPercode(menu.getPath().replaceAll("/", ":"));
        // menu.setPercode(menu.getPath().replaceAll("/", ""));

        String replaceFirst = menu.getPath().replaceFirst("/", "");
        menu.setPercode(replaceFirst.replaceAll("/",":"));
        String token = WebUtil.getToken();
        String phone = JwtUtils.getClaimByName(token);
        redisTemplate.delete("menu:leftMenu:" + phone);
        return menuMapper.updateById(menu);
    }

    /**
     * @return com.hos.entity.sys.User
     * @create by: 陈海彬
     * @description: 获取请求用户的信息
     * @create time: 2023/12/12 10:39
     */
    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userService.findUserByPhone(phone);
    }
}